import React from "react";
import {
  Modal,
  Button,
  Row,
  Card,
  Col,
  Table,
  Tree,
  Spin,
  Tooltip,
} from "antd";
import { connect } from "dva";
// import UserTree from "../../../../components/usertree/UserTree";
import styles from "./TenantUserAdd.less";

import { openNotificationWithIcon, getOrgArrs } from "../../utils/comm.js";

const { TreeNode } = Tree;

class TenantUserAdd extends React.Component {
  addCol = [];

  delCol = [];

  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.selectData = [];
    // this.loadedKeys = [];
    this.selectedKeysInvert = [];
    this.state = {
      treeData: [],
      selectedKeys: [],
      checkedNodes: [],
      deleteLoading: false,
    };
  }

  componentDidMount() {
    this.getRootOrg();
    this.getListUsers();
  }

  /*
  // 查询父节点路径
  findIndexArray = (data, code, indexArray) => {
    const arr = Array.from(indexArray);
    for (let i = 0, len = data.length; i < len; i += 1) {
      arr.push((data[i].extentAttributes || data[i].extentAttribute || {}).ORG_NAME || '');
      if (data[i].code === code) {
        return arr;
      }

      const { children } = data[i];
      if (children && children.length) {
        const result = this.findIndexArray(children, code, arr);
        if (result) return result;
      }
      arr.pop();
    }
    return false;
  };
  */

  getListUsers = () => {
    const { dispatch, id } = this.props;
    dispatch({
      type: "tenantManagement/listUsers",
      payload: { tenantId: id },
    }).then(({ errCode, errMsg, datas }) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon(
          "error",
          "",
          errMsg || "获取已关联租户的用户列表失败",
        );
      } else {
        // 数组去重
        const newCheckedNodes = this.remove(datas);
        this.setState({ checkedNodes: newCheckedNodes });
      }
    });
  };

  // 数组去重
  remove = (arr) => {
    const key = {};
    let newArr = [];
    newArr = arr.filter((item) => {
      if (key[item.userCode]) return false;
      key[item.userCode] = true;
      return true;
    });

    return newArr;
  };

  getRootOrg = () => {
    const { dispatch } = this.props;
    if (!dispatch) return;
    dispatch({
      type: "usertreeSelect/getRootOrg",
      payload: {},
    }).then(({ errCode, datas }) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon("error", "", "获取根组织信息失败");
      }
      // this.loadedKeys = this.loadedKeys.concat([datas]);
      this.setState({ treeData: Array.isArray(datas) ? datas : [datas] });
    });
  };

  onSelect = (selectedKeys, { selectedNodes }) => {
    const { checkedNodes, treeData } = this.state;
    const { code, displayName } = selectedNodes[0].props.dataRef;

    if (!code) return;

    const orgArr = getOrgArrs(treeData, code, []) || [];
    const arr = [
      {
        userCode: code,
        userName: displayName,
        userOrgDesc: orgArr.join("/"),
      },
    ];

    if (checkedNodes.some((item) => item.userCode === code)) return;
    const newCheckedNodes = checkedNodes.concat(arr);
    this.setState({ checkedNodes: newCheckedNodes });

    if (this.addCol.some((item) => item.userCode === code)) return;
    this.addCol = this.addCol.concat(arr);
  };

  handleLoadData = (treeNode) =>
    new Promise((resolve) => {
      const { dispatch } = this.props;
      const { treeData, selectedKeys } = this.state;
      if (treeNode.props.children) {
        resolve();
        return;
      }
      const orgCode = treeNode.props.dataRef.code;
      const orgName = treeNode.props.dataRef.displayName;
      dispatch({
        type: "usertreeSelect/getChildren",
        payload: { pageNo: 1, pageSize: 1000, orgCode, orgName },
      }).then(({ errCode, uerrCode, uerrMsg, errMsg, datas }) => {
        if (errCode !== 0) {
          this.openNotificationWithIcon(
            "error",
            "",
            errMsg || "获取子组织信息失败",
          );
        }
        if (uerrCode !== 0) {
          this.openNotificationWithIcon(
            "error",
            "",
            uerrMsg || "获取人员信息失败",
          );
        }
        if (datas.length > 0) {
          treeNode.props.dataRef.children = datas;
          // 反显处理
          const loadedSelectedKeys = this.selectedKeysInvert.filter((item) => {
            return datas.some((citem) => citem.code === item);
          });
          const newKeys = [...selectedKeys, ...loadedSelectedKeys];
          // this.loadedKeys = this.loadedKeys.concat(datas);
          this.setState({
            treeData: [...treeData],
            selectedKeys: newKeys,
          });
          resolve();
        }
        resolve();
      });
    });

  renderTreeNodes = (data) =>
    data.map((item) => {
      if (item.children) {
        return (
          <TreeNode
            selectable={!!item.isLeaf}
            title={item.displayName}
            key={item.code}
            dataRef={item}
          >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          selectable={!!item.isLeaf}
          title={item.displayName}
          key={item.code}
          dataRef={item}
          isLeaf={!!item.isLeaf}
        />
      );
    });

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { dispatch, id, onOk } = this.props;
    const { addCol, delCol } = this;
    const params = { tenantId: id, addCol, delCol };
    dispatch({
      type: "tenantManagement/submitUsers",
      payload: params,
    }).then(({ errCode, errMsg }) => {
      if (errCode === 0) {
        this.handleCancel(true);
        this.openNotificationWithIcon("success", "", "操作成功");
        if (onOk) {
          onOk();
        }
      } else {
        this.openNotificationWithIcon("warning", "", errMsg || "操作失败");
      }
    });
  };

  handleCancel = (isQuery) => {
    const { handleCancel } = this.props;
    handleCancel(false, isQuery);
  };

  tagClose = (removedTag) => {
    const { checkedNodes } = this.state;

    const aftercheckedNodes = checkedNodes.filter(
      (item) => item.userCode !== removedTag.userCode,
    );
    // 删除的是已有的用户,delCol 添加
    if (removedTag.id) {
      this.delCol = this.delCol.concat([
        {
          id: removedTag.id,
          userCode: removedTag.userCode,
        },
      ]);
    } else {
      // 删除的是新添加的用户
      this.addCol = this.addCol.filter(
        (item) => item.userCode !== removedTag.userCode,
      );
    }

    this.setState({ checkedNodes: aftercheckedNodes });
  };

  renderFooter = (confirmLoading) => {
    const { okText = '提交' } = this.props;
    return (
      <div>
        <Button style={{ marginRight: 10 }} onClick={this.handleCancel}>
          取消
        </Button>
        <Button
          loading={confirmLoading}
          type="primary"
          onClick={() => {
            this.handleOk();
          }}
        >
          { okText }
        </Button>
      </div>
    );
  };

  handleDelete = (record) => {
    const { dispatch, id } = this.props;
    const { userCode } = record;
    const self = this;
    this.setState({ deleteLoading: true });
    dispatch({
      type: "tenantManagement/getAuthorizedApp",
      payload: { tenantId: id, userCode },
    }).then(({ errCode, datas }) => {
      if (errCode === 0 && datas) {
        Modal.confirm({
          title: `该用户已授权${datas}，是否确定删除`,
          okText: "确定",
          cancelText: "取消",
          onOk() {
            self.tagClose(record);
          },
          onCancel() {},
        });
      } else {
        this.tagClose(record);
      }
      this.setState({ deleteLoading: false });
    });
  };

  render() {
    const { visible, confirmLoading } = this.props;
    const { checkedNodes, treeData, selectedKeys, deleteLoading } = this.state;

    const {
      loading: { effects },
      title = '用户管理',
    } = this.props;
    const rootLoading = effects["usertreeSelect/getRootOrg"] || false;
    // const deleteLoading = effects["usertreeSelect/getAuthorizedApp"] || false;

    const columns = [
      {
        title: "用户编号",
        dataIndex: "userCode",
      },
      {
        title: "组织名称",
        dataIndex: "userOrgDesc",
        render: (text) => {
          let _text = text;
          if (text && text.length > 10) {
            _text = `${text.substr(0, 10)}...`;
          }
          return (
            <>
              {text.length > 10 ? (
                <Tooltip overlayClassName={styles.tooltip} title={text}>
                  <span>{_text}</span>
                </Tooltip>
              ) : (
                <span>{text}</span>
              )}
            </>
          );
        },
      },
      {
        title: "姓名",
        dataIndex: "userName",
      },
      {
        title: "操作",
        render: (text, record) => {
          return (
            <a
              onClick={(e) => {
                e.preventDefault();
                this.handleDelete(record);
              }}
            >
              删除
            </a>
          );
        },
      },
    ];

    return (
      <Modal
        title={title}
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => {
          this.handleCancel(false);
        }}
        footer={this.renderFooter(confirmLoading)}
        width="800px"
        centered
        confirmLoading={confirmLoading}
        wrapClassName={styles.modal}
      >
        <Row style={{ height: 412 }}>
          <Col span={8}>
            <Card
              size="small"
              title="选择用户"
              style={{ height: "100%" }}
              bodyStyle={{ height: 373, overflow: "auto" }}
            >
              <Spin spinning={rootLoading}>
                <div className={styles.user_tree}>
                  {treeData.length > 0 && (
                    <Tree.DirectoryTree
                      loadData={this.handleLoadData}
                      onSelect={this.onSelect}
                      selectedKeys={selectedKeys}
                    >
                      {this.renderTreeNodes(treeData)}
                    </Tree.DirectoryTree>
                  )}
                </div>
              </Spin>
            </Card>
          </Col>
          <Col span={16}>
            <Card
              size="small"
              title="已选用户"
              style={{ height: "100%" }}
              bodyStyle={{ height: 373, overflow: "auto" }}
            >
              <Spin spinning={deleteLoading}>
                <Table
                  columns={columns}
                  dataSource={checkedNodes}
                  rowKey="userCode"
                  pagination={false}
                />
              </Spin>
            </Card>
          </Col>
        </Row>
      </Modal>
    );
  }
}
const ConnectTreeStore = (Component) => connect(({ usertreeSelect, loading }) => ({
  loading,
  usertreeSelectStore: usertreeSelect,
}))(Component);

export { TenantUserAdd as UserAdd, ConnectTreeStore };

export default ConnectTreeStore(TenantUserAdd);
